$(function () {
    window.startDate = $('#datePicker').find('.start').html();
    window.endDate = $('#datePicker').find('.end').html();

    var loading = $('#loading');
    var toggleLoading = function (isShow) {
        if (isShow) {
            loading.removeClass('hidden');
        } else {
            loading.addClass('hidden');
        }
    };

    var tip = function (obj, info) {
        obj.tip({
            content: info,
            background: "#000",
            color: "#fff"
        });
    };

    var orderStatusNameConstant = [lang('constant.notApply'), lang('constant.applyRefund'), lang('constant.refund'), lang('constant.reject')];
    var refundTypeNameConstant = ['', lang('constant.refundApply'), lang('constant.recede')];
    var refreshLayout = function (datas) {
        var orderInfos = datas.item;
        if (orderInfos.length === 0) {
            $('#orderListBody').html('');
            $('#orderListBodyEmpty').removeClass('hidden');
            $('#orderListPage').addClass('hidden');
        } else {
            $('#orderListBodyEmpty').addClass('hidden');
            var templateHTML = $($('#templateOrder').clone().html());
            var ordersHTML = '';
            $.each(orderInfos, function (key, orderInfo) {
                templateHTML.find('.order-number').html(orderInfo.orderNumber);
                templateHTML.find('.order-user-info').html(orderInfo.user.name).attr('title', orderInfo.user.name + '<br/>' + orderInfo.user.mobile);
                templateHTML.find('.order-total').html(orderInfo.price);
                templateHTML.find('.order-refund-price').html(orderInfo.refundPrice);
                templateHTML.find('.order-charityprice').html(orderInfo.charityPrice);
                templateHTML.find('.order-room-info').html((orderInfo.roomName).split(',')[0]).attr('title', orderInfo.roomName + '<br/><br/>' + orderInfo.roomTypeName);
                templateHTML.find('.order-room-info').next('.iconfont').attr('title', orderInfo.roomName + '<br/><br/>' + orderInfo.roomTypeName);
                templateHTML.find('.order-checkin-date').html(orderInfo.startDate);
                templateHTML.find('.order-checkout-date').html(orderInfo.endDate);
                var currentOrderStatus = parseInt(orderInfo.status);
                var refundType = parseInt(orderInfo.type);
                var realStatusName = orderStatusNameConstant[currentOrderStatus];
                var refundTypeName = refundTypeNameConstant[refundType];
                templateHTML.find('.order-status').html(realStatusName);
                templateHTML.find('.order-refund-type').html(refundTypeName);
                templateHTML.find('.refund-reason').html(orderInfo.reason).attr('title', orderInfo.reason + '<br/>' + orderInfo.apply);
                templateHTML.find('.order-refund-action').attr('data-value', key);
                if (currentOrderStatus === 1) {
                    templateHTML.find('.order-refund-action div').removeClass('hidden');
                } else {
                    templateHTML.find('.order-refund-action div').addClass('hidden');
                }
                if (refundType == 2) {
                    templateHTML.find('.refuseRefundBtn').addClass('hidden');
                }
                ordersHTML += templateHTML.prop('outerHTML');
            });
            $('#orderListBody').html(ordersHTML);
            $('[data-toggle="tooltip"]').tooltip();
            var pageInfo = datas.page;
            var currentPage = parseInt(pageInfo.currentPage);
            var pages = parseInt(pageInfo.total);
            var pageContainer = $('#orderListPage');
            pageContainer.removeClass('hidden');
            var pageHTML = '';
            var templatePage = $($('#templatePage').clone().html());
            for (var i = 1; i <= pages; i++) {
                if (currentPage === i) {
                    templatePage.addClass('active');
                } else {
                    templatePage.removeClass('active');
                }
                templatePage.find('a').html(i).attr('data-value', i);
                pageHTML += templatePage.prop('outerHTML');
            }
            pageContainer.find('.pagination').html(pageHTML);
            pageContainer.find('.page-count').html(pages);
            pageContainer.find('.page-total').html(pageInfo.totalCount);
        }
    };
    var requestInfo = function (page, status, statDate, endDate, mobile, submitBtn) {
        window.lastRequestStatus = status;
        window.lastRequestStart = statDate;
        window.lastRequestEnd = endDate;
        window.lastRequestMobile = mobile;
        toggleLoading(true);
        var params = {
            'hotel': window.currentHotel,
            'currentPage': page,
            'startDate': statDate,
            'endDate': endDate
        };
        if (status !== 0) {
            params.status = status;
        }
        if (mobile !== '') {
            params.mobile = mobile;
        }
        ajaxRequest('/Home/Hotel/refundItem', params, 'post', function (data) {
            toggleLoading(false);
            window.serverDatas = data.data;
            refreshLayout(window.serverDatas);
        }, function (error, obj) {
            toggleLoading(false);
            if (typeof error.responseJSON == 'undefined') {
                tip(obj, lang('tip.system'));
                return;
            }

            tip(obj, error.responseJSON.info);
        }, submitBtn);
    };

    requestInfo(1, 0, window.startDate, window.endDate, '', $('#filterSearch'));

    $('#orderListPage .pagination').on('click', 'li:not(.active) a', function () {
        var pageIndex = $(this).data('value');
        var submitBtn = $('#filterSearch');
        requestInfo(pageIndex, window.lastRequestStatus, window.lastRequestStart, window.lastRequestEnd, window.lastRequestMobile, submitBtn);
    });

    $('#filterHeader').on('click', '.dropdown-menu li>a', function (e) {
        var item = $(this);
        var liItem = item.parents('li');
        var toggle = liItem.parents('.dropdown-menu').siblings('[data-toggle="dropdown"]');
        liItem.addClass('active');
        liItem.siblings().removeClass('active');
        var value = liItem.data('value');
        var name = item.text();
        toggle.data('value', value);
        toggle.find('.info').html(name);
    });

    // 选择日期
    var format = 'YYYY-MM-DD';
    $('#datePickerInput').daterangepicker({
        'showDropdowns': true,
        'autoApply': true,
        'dateLimit': {
            'days': 30
        },
        'locale': {
            'format': format,
            'applyLabel': lang('date.ensure'),
            'cancelLabel': lang('date.cancel'),
            'daysOfWeek': [
                lang('week.7'),
                lang('week.1'),
                lang('week.2'),
                lang('week.3'),
                lang('week.4'),
                lang('week.5'),
                lang('week.6')
            ],
            'monthNames': [
                lang('month.1'),
                lang('month.2'),
                lang('month.3'),
                lang('month.4'),
                lang('month.5'),
                lang('month.6'),
                lang('month.7'),
                lang('month.8'),
                lang('month.9'),
                lang('month.10'),
                lang('month.11'),
                lang('month.12')
            ],
            'firstDay': 1
        },
        'linkedCalendars': false,
        'parentEl': 'body',
        'startDate': window.startDate,
        'endDate': $('#datePicker').find('.end').html(),
        'minDate': '2000-01-01',
        'maxDate': '2038-01-01'
    }, function (start, end, label) {
        window.startDate = start.format(format);
        window.endDate = end.format(format);
        $('#datePicker').find('.start').html(window.startDate);
        $('#datePicker').find('.end').html(window.endDate);
    });
    $('#datePicker').on('click', function () {
        $('#datePickerInput').trigger('focus');
    });

    // 查询筛选
    $('#filterSearch').on('click', function () {
        var filterStatus = $('#filterType').data('value');
        var filterMobile = $('#filterMobile').val().trim();
        if (filterMobile !== '' && !window.commonRegexp.mobile.test(filterMobile)) {
            tip($('#filterMobile'), lang('tip.mobile'));
            return;
        }
        var submitBtn = $(this);
        requestInfo(1, filterStatus, window.startDate, window.endDate, filterMobile, submitBtn);
    });

    // 确认退款
    $('#refundModal').on('show.bs.modal', function (e) {
        ajaxRequest('/Home/Hotel/getPayDetail', {
            hotel: window.currentHotel
        }, 'post', function (data) {


            var triggerBtn = $(e.relatedTarget);
            var itemIndex = triggerBtn.parents('.order-refund-action').data('value');
            var orderInfo = window.serverDatas.item[itemIndex];
            var deposit = data.data.deposit,
                refundRule = data.data.refundrule;

            var modal = $('#refundModal');
            modal.find('.refund-order-number').html(orderInfo.orderNumber);
            modal.find('.refund-rule').html(refundRule);
            modal.find('.deposit').html(deposit);
            $('#requestRefund').val(deposit);
            var userName = orderInfo.user.name;
            if (userName === null || userName === '') {
                userName = lang('constant.wu');
            }
            modal.find('.refund-order-user').html(userName);
            var userMobile = orderInfo.user.mobile;
            if (userMobile === null || userMobile === '') {
                userMobile = lang('constant.wu');
            }
            modal.find('.refund-order-user-mobile').html(userMobile);
            modal.find('.refund-order-total').html(orderInfo.price);
            modal.find('.refund-order-charityprice').html(orderInfo.charityPrice);
            formInlineRight($('#requestRefund'));
            formInlineRight($('#submitRefund'));
            $('#submitRefund').data('value', orderInfo.id);
            $('#submitRefund').data('index', itemIndex);
        }, function(error) {});
    });

    $('#refundModal').inputValidate({
        submit: {
            query: '#submitRefund'
        },
        inputs: [{
            query: '#requestRefund',
            regexp: window.commonRegexp.roomTypePrice,
            message: lang('constant.sum'),
            emptyMessage: lang('constant.sumNull')
        }]
    });

    $('#submitRefund').on('successSubmit.amos.inputValidate', function (e) {
        var decimal = $('#requestRefund').val();
        if (parseFloat(decimal) <= 0 || parseFloat(decimal) > 999999.99) {
            formInlineTip($('#requestRefund'), lang('constant.sum'));
            return;
        }
        var submitBtn = $(this);
        var params = {};
        params.hotel = window.currentHotel;
        params.refund = submitBtn.data('value');
        params.price = decimal;
        ajaxRequest('/Home/Order/agreeRefund', params, 'post', function (data) {
            var itemIndex = submitBtn.data('index');
            window.serverDatas.item[itemIndex].status = 2;
            window.serverDatas.item[itemIndex].refundPrice = decimal;
            refreshLayout(window.serverDatas);
            $('#refundModal').modal('hide');
        }, null, submitBtn);
    });

    // 驳回
    $('#rejectModal').on('show.bs.modal', function (e) {
        var triggerBtn = $(e.relatedTarget);
        var itemIndex = triggerBtn.parents('.order-refund-action').data('value');
        var orderInfo = window.serverDatas.item[itemIndex];

        var modal = $('#rejectModal');
        modal.find('.reject-order-number').html(orderInfo.orderNumber);
        var userName = orderInfo.user.name;
        if (userName === null || userName === '') {
            userName = lang('constant.wu');
        }
        modal.find('.reject-order-user').html(userName);
        var userMobile = orderInfo.user.mobile;
        if (userMobile === null || userMobile === '') {
            userMobile = lang('constant.wu');
        }
        modal.find('.reject-order-user-mobile').html(userMobile);
        modal.find('.reject-order-total').html(orderInfo.price);
        $('#requestRejectReason').val('');
        formInlineRight($('#requestRejectReason'));
        formInlineRight($('#submitReject'));
        $('#submitReject').data('value', orderInfo.orderRoomId);
        $('#submitReject').data('index', itemIndex);
    });

    $('#rejectModal').inputValidate({
        submit: {
            query: '#submitReject'
        },
        inputs: [{
            query: '#requestRejectReason',
            regexp: /.{1,50}/,
            message: lang('requestRejectReason'),
            emptyMessage: lang('requestRejectReasonNull')
        }]
    });

    $('#submitReject').on('successSubmit.amos.inputValidate', function (e) {
        var submitBtn = $(this);
        var applyInfo = $('#requestRejectReason').val();
        var params = {};
        params.hotel = window.currentHotel;
        params.orderRoomId = submitBtn.data('value');
        params.apply = applyInfo;
        ajaxRequest('/Home/Order/refuseRefund', params, 'post', function (data) {
            var itemIndex = submitBtn.data('index');
            window.serverDatas.item[itemIndex].status = 3;
            window.serverDatas.item[itemIndex].apply = applyInfo;
            refreshLayout(window.serverDatas);
            $('#rejectModal').modal('hide');
        }, null, submitBtn);
    });
});
